<template>
<div>
    <div class="line"></div>
    <div class="option-box m-tb-20" style="text-align: left">
        <el-row :gutter="20">
            <el-col :span="16">
                <table class="option-table">
                    <tr v-for="(optionItem,i) in SKU_option" :key="i" class="m-tb-20">
                        <td width="30">
                            <el-tag @close="handleCloseGroup(optionItem.title)" type="info" effect="dark" closable>
                                {{optionItem.title}}
                            </el-tag>
                        </td>
                        <td width="100%">
                            <el-tag class="tag" :class="{'tag-cur':setImg_tag_index==i_tag&&setImg_index==i}" @click="selectTag(i,i_tag)" :key="i_tag" v-for="(tag,i_tag) in optionItem.value" closable :disable-transitions="false" @close="handleClose(tag.name,i)">
                                {{tag.name}}
                            </el-tag>
                            <el-input class="input-new-tag" v-show="inputVisible[i]" v-model="inputValue.name" :ref="'saveTagInput'+i" size="small" @keyup.enter.native="handleInputConfirm(i)" @blur="handleInputConfirm(i)">
                            </el-input>
                            <el-button v-show="!inputVisible[i]" class="button-new-tag" size="small" @click="showInput(i)">新增</el-button>
                        </td>
                        <td width="40">
                            <el-button size="small" class="manage-img-btn" plain @click="setImgColumn(i)">为这个字段设置图片</el-button>
                        </td>
                    </tr>
                </table>
            </el-col>
            <el-col :span="8">
                <upLoadSKUImg class="uploader" :url="tagImgUrl" @cb="setTagImg" v-show="showUpLoadSKUImg" />
            </el-col>
        </el-row>

        <el-input class="input-new-tag" v-show="inputAddOne" v-model="inputAddOneValue" ref="tagInputGroup" size="small" @keyup.enter.native="handleInputConfirmGroup" @blur="handleInputConfirmGroup">
        </el-input>
        <el-button type="primary" icon="el-icon-circle-plus-outline" size="mini" v-show="!inputAddOne" @click="addOne">新增一项</el-button>

        <!-- <el-button type="primary" icon="el-icon-circle-check" size="mini" v-show="!inputAddOne" @click="doExchangeAppend">追加到SKU</el-button> -->
    </div>

<!--    <el-button type="danger" icon="el-icon-check"-->
<!--               size="mini"-->
<!--               style="margin-left: 0"-->
<!--               class="init-sku" v-show="!inputAddOne" @click="doExchange">重置SKU</el-button>-->
<!--    <div class="line"></div>-->
    <div class="line"></div>
    <el-row class="m-tb-20" style="text-align: left">
        <el-button size="mini" type="danger" @click="delSelect">删除选中项</el-button>
        <el-popover class="m-lr-20" placement="top" width="160" v-model="commonPricevisible">
            <el-input class="input-price" v-model="priceInputCommon" ref="priceInputCommon" size="small">
            </el-input>
            <div style="text-align: right; margin: 0">
                <el-button size="mini" type="text" @click="commonPricevisible = false">取消</el-button>
                <el-button type="primary" size="mini" @click="setPrice">确定</el-button>
            </div>
            <el-button slot="reference" size="mini" type="primary">选中项统一标价</el-button>
        </el-popover>
        <el-popover placement="top" width="188" v-model="showUselessSuer">
            <p class="m-tb-20 color-red">删除列表中没有标价的项目，是否确定？</p>
            <div style="text-align: right; margin: 0">
                <el-button size="mini" type="text" @click="showUselessSuer = false">取消</el-button>
                <el-button type="primary" size="mini" @click="delUseless">确定</el-button>
            </div>
            <el-button size="mini" type="primary" slot="reference">删除无效项</el-button>
        </el-popover>
            <!-- <el-button size="mini" type="danger">去除无效的商品选项</el-button> -->
    </el-row>
    <div class="sku-box m-tb-20">
        <el-table ref="multipleTable" border :data="SKU_Table" tooltip-effect="dark" style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column prop="title" label="规格">
            </el-table-column>
            <el-table-column label="价格" width="140">
                <template slot-scope="scope">
                    <el-input class="input-new-tag" v-model="scope.row.price" size="small">
                    </el-input>
                </template>
            </el-table-column>

            <el-table-column label="库存" width="140">
                <template slot-scope="scope">
                    <el-input class="input-new-tag" v-model="scope.row.store" size="small">
                    </el-input>
                </template>
            </el-table-column>
            <el-table-column width="120">
                <template slot-scope="scope">
                    <el-button type="danger" size="mini" @click="handleDeleteRow(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>

</div>
</template>

<script>
import upLoadSKUImg from "@/common/upLoadSKUImg.vue";

export default {
    name: 'SKU',
    props: {
        cb: Function,
        SKU: {
            type: Object,
        },

        rules: {
            type: [Object, Array],
            default: () => []
        },
    },
    data() {
        return {
            SKU_OBJ: [], //商品信息集合[{title:"红色+大"，price:"500.00" , store:"200" ,  selected:false}]
            SKU_Table: [], //商品信息集合[{title:"红色+大"，price:"500.00" , store:"200" ,  selected:false}]
            SKU_option: [], // 选项[{title:"颜色",value:["红色","白色","绿色","灰色"]}]
            SKU_rules: this.rules, //商品信息集合验证规则

            inputVisible: [false, false], //输入显示
            inputAddOne: false, //输入显示,头
            inputValue: {}, //输入一个
            inputAddOneValue: '', //输入一组的最左的一个

            multipleSelection: [], //选中的规格

            commonPricevisible: false, //统一标价输入框

            priceInputCommon: 0, //统一价格

            showUselessSuer: false, //显示删除无效项确认

            setImg_index: -1, //当前设置图片的栏目下标

            setImg_tag_index: -1, //当前设置图片的tag下标

            tagImgUrl: "", //当前tag的图片

            showUpLoadSKUImg: false, //显示图片上传框

        }
    },
    components: {
        upLoadSKUImg
    },
    methods: {

        handleClose(tag, i) { //关闭tag
            this.SKU_option[i].value.splice(this.SKU_option[i].value.findIndex((e) => e.name == tag), 1);
            this.doExchangeReduce();
        },
        handleCloseGroup(title) { //关闭总的按钮
            this.SKU_option.splice(this.SKU_option.indexOf(title), 1);
            this.doExchangeReduce();
        },

        showInput(i) { //新增tag

            this.$set(this.inputVisible, i, true);
            this.$nextTick(_ => {
                this.$refs['saveTagInput' + i][0].focus();
            });
        },

        handleInputConfirm(i) { //确定添加按钮
var vm=this;
            if (vm.SKU_option[i].value.length == 0) {
                vm.$confirm('会清空原来的数据并从新生成新的SKU，是否继续？')
                    .then(function() {
                        {
                            let inputValue = vm.inputValue;
                            if (inputValue.name) {
                                vm.SKU_option[i].value.push(inputValue); //issue
                                vm.inputVisible[i] = false;
                                vm.inputValue = {};
                                vm.doExchange(); //添加一个tag就把新的SKU追加后面
                            } else {
                                vm.inputVisible[i] = false;
                            }
                        }
                        done();
                    })
                    .catch(function() {
                        vm.inputVisible=vm.inputVisible.map((e)=>e=false);
                    });
            } else {
                {
                    let inputValue = vm.inputValue;
                    if (inputValue.name) {
                        vm.SKU_option[i].value.push(inputValue); //issue
                        vm.inputVisible[i] = false;
                        vm.inputValue = {};
                        vm.doExchangeAppend(); //添加一个tag就把新的SKU追加后面
                    } else {
                        vm.inputVisible[i] = false;

                    }
                }
            }

        },
        handleInputConfirmGroup() { //确定添加按钮·
            if (!this.inputAddOneValue) {
                this.inputAddOne = false;
                return;
            }
            this.SKU_option.push({
                title: this.inputAddOneValue,
                value: []
            });
            this.inputAddOneValue = "";
            this.inputAddOne = false;
        },
        addOne() { //确定添加一个字段

            this.inputAddOne = true;
            this.$nextTick(() => {
                this.$refs.tagInputGroup.focus();
            });
        },

        handleSelectionChange(val) { //选择SKU

            this.multipleSelection = val;
        },

        handleDeleteRow(index, row) { //删除行
            this.SKU_Table.splice(index, 1);
        },

        //     handleRemove(file, fileList) {
        //     console.log(file, fileList);
        //   },
        //   handlePreview(file) {
        //     console.log(file);
        //   },
        //   handleExceed(files, fileList) {
        //     this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
        //   },
        //   beforeRemove(file, fileList) {
        //     return this.$confirm(`确定移除 ${ file.name }？`);
        //   },
        delSelect() { //删除所选
            this.SKU_Table = this.SKU_Table.filter(e => {
                return !this.multipleSelection.some(el => el.title == e.title);
            })
        },

        setImgColumn(i) { //点击设置这个字段的图片
            this.setImg_tag_index = 0;
            this.setImg_index = i;
        },

        setPrice() { //设置价格

            this.commonPricevisible = false;
            this.SKU_Table.map(e => {
                this.multipleSelection.map(el => {
                    if (e.title == el.title) {
                        e.price = this.priceInputCommon;
                    }
                })
            })
        },

        delUseless() { //删除
            this.SKU_Table = this.SKU_Table.filter(e => e.price);
            this.showUselessSuer = false;
        },

        selectTag(i, i_tag) {
            this.setImg_index = i;
            this.setImg_tag_index = i_tag;
        },

        setTagImg(url) {
            this.SKU_option.forEach((e, i) => {
                e.value.forEach((el, i_tag) => {
                    if (this.setImg_tag_index == i_tag && this.setImg_index == i) {
                        el.pic = url;
                    }
                })
            });
            this.SKU_option[this.setImg_index];
            this.setImg_tag_index++;
            if (this.SKU_option[this.setImg_index].value.length <= this.setImg_tag_index) {
                this.setImg_tag_index = this.SKU_option[this.setImg_index].value.length - 1;
            }
        },

        reDoTag() {

        },

        doExchangeAppend() {
            var arr = [];
            this.SKU_option.map(e => {
                if (e.value.length == 0) return;
                arr.push(e.value.map(e => e.name));
            });
            var result = [];
            var results = [];

            function exchange(arr, depth) { //匹配算法
                for (var i = 0; i < arr[depth].length; i++) {
                    result[depth] = arr[depth][i]
                    if (depth != arr.length - 1) {
                        exchange(arr, depth + 1)
                    } else {
                        results.push(result.join('+'))
                    }
                }
            }

            exchange(arr, 0);

            results.map(e => {
                var find = this.SKU_Table.some((el) => el.title == e);
                if (find) return;
                this.SKU_Table.push({
                    title: e,
                    price: "",
                    pic: "",
                    store: "",
                });
            })
        },

        doExchange() { //执行匹配算法
            var arr = [];
            this.SKU_option.map(e => {
                if (e.value.length == 0) return;
                arr.push(e.value.map(e => e.name));
            });
            var result = [];
            var results = [];
            if (!arr.length) {
                this.$message.error("请输入商品SKU！");
                return;
            }

            function exchange(arr, depth) { //匹配算法
                for (var i = 0; i < arr[depth].length; i++) {
                    result[depth] = arr[depth][i]
                    if (depth != arr.length - 1) {
                        exchange(arr, depth + 1)
                    } else {
                        results.push(result.join('+'))
                    }
                }
            }

            exchange(arr, 0);
            this.SKU_Table = [];
            results.map(e => {
                this.SKU_Table.push({
                    title: e,
                    price: "",
                    pic: "",
                    store: "",
                });
            })
        },

        doExchangeReduce() { //减
            var arr = [];
            this.SKU_option.map(e => {
                if (e.value.length == 0) return;
                arr.push(e.value.map(e => e.name));
            });
            var result = [];
            var results = [];

            function exchange(arr, depth) { //匹配算法
                for (var i = 0; i < arr[depth].length; i++) {
                    result[depth] = arr[depth][i]
                    if (depth != arr.length - 1) {
                        exchange(arr, depth + 1)
                    } else {
                        results.push(result.join('+'))
                    }
                }
            }
            exchange(arr, 0);

            var temp = [];
            results.map(e => {
                this.SKU_Table.map(el => {
                    if (el.title == e) {
                        temp.push(el);
                    }
                });
            })
            this.SKU_Table = temp;

        },

        emit() { //提交
            this.$emit("cb", {
                SKU: this.SKU_Table,
                option: this.SKU_option
            });
        },
    },
    watch: {
        SKU: {
            handler(val) {
                if (JSON.stringify(val) == "{}" || !val) {
                    val = {
                        option: [],
                        SKU: []
                    }
                };
                var a_string = JSON.stringify(val);
                var b_string = JSON.stringify({
                    SKU: this.SKU_Table,
                    option: this.SKU_option
                });
                if (a_string.length == b_string.length && a_string == b_string) { //限制死循环
                    return;
                }
                this.SKU_OBJ = val.SKU || [];
                this.SKU_Table = val.SKU || [];
                this.SKU_option = val.option || [];
            },
            immediate: true
        },

        setImg_tag_index(val) {
            var url = "";
            this.showUpLoadSKUImg = false;
            if (!this.SKU_option[this.setImg_index]) {
                return;
            };
            if (this.SKU_option[this.setImg_index].value.length <= this.setImg_tag_index) {
                this.tagImgUrl = "";
                return;
            }
            if (this.setImg_tag_index < 0) {
                this.tagImgUrl = "";
                return;
            }
            this.showUpLoadSKUImg = true;
            this.SKU_option.forEach((e, i) => {
                e.value.forEach((el, i_tag) => {
                    if (this.setImg_tag_index == i_tag && this.setImg_index == i) {
                        url = el.pic || "";
                    }
                })
            })

            this.tagImgUrl = url;
        },
        setImg_index(val) {
            var url = "";
            this.showUpLoadSKUImg = false;
            if (!this.SKU_option[this.setImg_index]) return;
            if (this.SKU_option[this.setImg_index].value.length <= this.setImg_tag_index) {
                this.tagImgUrl = "";
                return;
            }
            if (this.setImg_tag_index < 0) {
                this.tagImgUrl = "";
                return;
            }
            this.showUpLoadSKUImg = true;
            this.SKU_option.forEach((e, i) => {
                e.value.forEach((el, i_tag) => {
                    if (this.setImg_tag_index == i_tag && this.setImg_index == i) {
                        url = el.pic || "";
                    };
                })
            })
            this.tagImgUrl = url;
        },
        SKU_Table: {
            handler(val) {
                this.emit();
            },
            deep: true
        },
        SKU_option: {
            handler(val) {
                this.emit();
            },
            deep: true
        }
    },
    computed: {},
    created() {},
    mounted() {
        //issue 删除一个tag 提示删除对应的SKU
    },
}
</script>

<style lang="less" scoped>
.button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
}

.input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
}

.m-tb-20 {
    margin-top: 20px;
    margin-bottom: 20px;
}

.m-lr-20 {
    margin-left: 20px;
    margin-right: 20px;
}

.input-price {
    margin: 20px auto;
    width: 162px;
}

.color-red {
    color: #f00;
}

.line {
    height: 1px;
    border-bottom: 1px dashed #bbb;
    margin: 20px 0;
}

@table-left: 5px;

.el-tag,
.el-input__inner {
    margin: 5px @table-left;
    padding: 0 30px;
}

.input-new-tag {
    margin: 5px @table-left;
}

.option-table {

    margin-bottom: 20px;
    margin-left: -1*@table-left;
    width: 100%;

    td {
        vertical-align: top;
        padding-right: 4px;
    }

    .manage-img-btn,
    .button-new-tag {
        margin-top: @table-left;
    }

    /deep/ .el-tag .el-icon-close {
        right: -28px;
        padding: 3px;
    }

}

.uploader {
    padding: @table-left;

}

.tag {
    cursor: pointer;
}

.tag-cur {
    border: 1px solid #005dff;
}

.init-sku {
    margin: auto;
    display: block;
}
</style>
